//获取应用实例
const app = getApp();

Page({
  data: {
    bannerList: [{}],
    tempBannerList: [{}],
    motto: '',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    navData: [],
    page: 1,
    bkshopList: [{
      skuName: ''
    }, {
      skuName: ''
    }, {
      skuName: ''
    }, {
      skuName: ''
    }, {
      skuName: ''
    }, {
      skuName: ''
    }],
    currentTab: 0,
    navScrollLeft: 0,
    //准备数据 
    menu: {},
    goodsList: [],
    jyshopList: [],
    quanprice: 0,
    shows: false, //控制下拉列表的显示隐藏，false隐藏、true显示
    selectDatas: [{
      name: '全部',
      id: ''
    }, {
      name: '中石化',
      id: '2'
    }, {
      name: '中石油',
      id: '1'
    }, {
      name: '壳牌',
      id: '3'
    }], //下拉列表的数据
    indexs: 0, //选择的下拉列 表下标,

    shows1: false, //控制下拉列表的显示隐藏，false隐藏、true显示
    selectDatas1: [{
      name: '92号油',
      id: '92'
    }, {
      name: '95号油',
      id: '95'
    }, {
      name: '98号油',
      id: '98'
    }, {
      name: '0号油',
      id: '0'
    }], //下拉列表的数据
    indexs1: 0, //选择的下拉列 表下标,

    shows2: false, //控制下拉列表的显示隐藏，false隐藏、true显示
    selectDatas2: [{
      name: '全部',
      id: ''
    }, {
      name: '1千米',
      id: '1000'
    }, {
      name: '3千米',
      id: '3000'
    }, {
      name: '5千米',
      id: '5000'
    }, {
      name: '10千米',
      id: '10000'
    }, {
      name: '20千米',
      id: '20000'
    }, {
      name: '30千米',
      id: '30000'
    }], //下拉列表的数据
    indexs2: 0, //选择的下拉列 表下标,
    latitude: '',
    longitude: '',
    leixing: '', //加油站
    youhao: '', //油号
    juli: '', //距离

  },
  onLoad: function () {
    var that = this;
    //调用定位方法
    that.getUserLocation();
    this.getUserMsg();
    // that.getTopGoodsList();
    wx.getStorage({
      key: 'token',
      success: function (res) {
        console.log(res)
        if (res.data != '') {
          app.globalData.token = res.data
        }
        console.log("token=" + app.globalData.token)
      },
    })

    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }

    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          pixelRatio: res.pixelRatio,
          windowHeight: res.windowHeight,
          windowWidth: res.windowWidth
        })
      },
    })
  },
  //获取用户信息
  getUserMsg() {
    wx.showLoading({
      title: '加载中',
      mask: false
    })
    console.log(app.globalData.token)
    var that = this;
    wx.request({
      url: app.globalData.api + '/app.php?c=User&a=getUserMsg',
      data: {
        token: app.globalData.token
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        console.log(res);
        wx.hideLoading();
        if (res.data.code == 0) {
          app.globalData.phone = res.data.data.user_msg.phone
        } else {
          // if (res.data.code == 105) {
          wx.removeStorage({
            key: 'token',
            success: function (res) {
              console.log(res)
            },
          })
          app.globalData.token = '';
          wx.reLaunch({
            url: '/pages/mine/login',
          })
          // }
        }
      },
      fail: function () {

      },
      complete: function () {

      }
    });
  },

  //定位方法

  getUserLocation: function () {
    var _this = this;
    wx.getSetting({
      success: (res) => {
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        console.log(res)
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          //未授权
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                //取消授权
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                //确定授权，通过wx.openSetting发起授权请求
                wx.openSetting({
                  success: function (res) {
                    if (res.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      _this.geo();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //用户首次进入页面,调用wx.getLocation的API
          _this.geo();
        } else {
          console.log('授权成功')
          //调用wx.getLocation的API
          _this.geo();
        }
      }
    })
  },
  // 获取定位城市

  geo: function () {
    var that = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log(res)
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy
        that.setData({
          latitude: latitude,
          longitude: longitude
        })
        that.getTopCatList();
      }
    })
  },
  // 点击下拉显示框   加油站
  selectTaps() {
    this.setData({
      shows: !this.data.shows,
    });
  },
  // 点击下拉列表 
  optionTaps(e) {
    let Indexs = e.currentTarget.dataset.index; //获取点击的下拉列表的下标
    console.log(Indexs)
    this.setData({
      indexs: Indexs,
      leixing: e.currentTarget.dataset.id,
      shows: !this.data.shows
    });
    this.getTopCatList();
  },

  // 点击下拉显示框  石油类型
  selectTaps1() {
    this.setData({
      shows1: !this.data.shows1,
    });
  },
  // 点击下拉列表   
  optionTaps1(e) {
    let Indexs = e.currentTarget.dataset.index; //获取点击的下拉列表的下标
    console.log(Indexs)
    this.setData({
      indexs1: Indexs,
      youhao: e.currentTarget.dataset.id,
      shows1: !this.data.shows1
    });
    this.getTopCatList();
  },

  // 点击下拉显示框   距离
  selectTaps2() {
    this.setData({
      shows2: !this.data.shows2,
    });
  },
  // 点击下拉列表
  optionTaps2(e) {
    let Indexs = e.currentTarget.dataset.index; //获取点击的下拉列表的下标
    console.log(Indexs)
    this.setData({
      indexs2: Indexs,
      juli: e.currentTarget.dataset.id,
      shows2: !this.data.shows2
    });
    this.getTopCatList();
  },


  //获取顶级京东商品分类列表
  getTopGoodsList() {
    wx.showLoading({
      title: '加载中',
      mask: false
    })
    var that = this;
    var navDatas = [{
      icon: '',
      is_show: '',
      name: '爆款',
      pid: '',
      sort: '',
      taobao_cat_id: '',
      tb_cat_id: ''
    }]
    wx.request({
      url: app.globalData.api + '/app.php?c=JingdongCat&a=getTopCatList',
      data: {
        token: app.globalData.token
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        console.log(res);
        wx.hideLoading();

        that.setData({
          navData: navDatas.concat(res.data.data.list),

        })

        that.getTopCatList(0);
      },
      fail: function () {
        wx.hideLoading();
      }
    });
  },
  //获取加油站列表
  getTopCatList() {
    wx.showLoading({
      title: '加载中',
      mask: false
    })
    var that = this;
    var lats = that.data.longitude + ',' + that.data.latitude;
    console.log(lats)
    console.log(app.globalData.phone)
    wx.request({
      url: app.globalData.apiJy + '/app.php?c=Gas&a=getGasList',
      data: {
        phone: app.globalData.phone,
        lng_lat: lats,
        page: that.data.page,
        per: 10,
        cond: 2,
        oilNo: that.data.youhao,
        gasType: that.data.leixing,
        distinct: that.data.juli,
      },
      header: {
        'Content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        // console.log(data)
        console.log(res.data);
        wx.hideLoading();
        if (res.data.code == 0) {
          for (var i = 0; i < res.data.data.list.length; i++) {
            res.data.data.list[i].distance = (res.data.data.list[i].distance / 1000).toFixed(2)
            res.data.data.list[i].priceofficial = (res.data.data.list[i].priceofficial - res.data.data.list[i].priceyfq).toFixed(2)
          }
          that.setData({
            jyshopList: that.data.jyshopList.concat(res.data.data.list),
          })
          console.log(that.data.jyshopList)
        } else {
          wx.showToast({
            title: '' + res.data.message,
            icon: 'none'
          })
          // that.setData({
          //   bkshopList:[]
          // })
        }
      },
      fail: function () {
        wx.hideLoading();
      }
    });
  },

  //导航
  toLocation: function (e) {
    wx.openLocation({
      latitude: Number(this.data.jyshopList[e.currentTarget.dataset.index].gasaddreslatitude),
      longitude: Number(this.data.jyshopList[e.currentTarget.dataset.index].gasaddresslongitude),
      name: this.data.jyshopList[e.currentTarget.dataset.index].gasaddress
    })
  },

  toTbkdetail: function (e) {
    console.log(e)
    console.log(this.data.jyshopList[e.currentTarget.dataset.index].gasaddress)
    wx.navigateTo({
      url: '/pages/live/jiayou-detail?&addres=' + this.data.jyshopList[e.currentTarget.dataset.index].gasaddress + '&id=' + e.currentTarget.dataset.id + '&img=' + this.data.jyshopList[e.currentTarget.dataset.index].gaslogobig
    })
  },
  toDetail: function (e) {
    console.log(e)
  },
  onShow() {

  },
  switchNav(event) {
    var cur = event.currentTarget.dataset.current;
    //每个tab选项宽度占1/5
    var singleNavWidth = this.data.windowWidth / 5;
    //tab选项居中                            
    this.setData({
      navScrollLeft: (cur - 2) * singleNavWidth
    })
    if (this.data.currentTab == cur) {
      return false;
    } else {
      this.setData({
        currentTab: cur
      })
    }
    console.log(event)
    console.log(this.data.navData)
    console.log(event.currentTarget.dataset.current)
    console.log(this.data.navData[event.currentTarget.dataset.current])
    this.getTopCatList(this.data.navData[this.data.currentTab].jingdong_id);
  },

  switchTab(event) {
    var cur = event.detail.current;
    var singleNavWidth = this.data.windowWidth / 5;
    this.setData({
      currentTab: cur,
      navScrollLeft: (cur - 2) * singleNavWidth
    });
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      page: 1,
      jyshopList: []
    })
    this.getTopCatList();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log("滑到底部了")
    this.setData({
      page: this.data.page + 1
    })
    this.getTopCatList();
  },
});